package com.huage_02.lesson_01;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JDBCDemo02 {
    public static void main(String[] args) {

        List<Student> list = findAll();
        System.out.println(list);
    }
    public static List<Student> findAll(){
        List<Student> list = new ArrayList<Student>();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql:///test?serverTimezone=GMT", "root", "root");

            String sql = "select * from student_info";
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            Student std = null;
            while (rs.next()){
                String name = rs.getString("name");
                String sex = rs.getString("sex");

                std = new Student();
                std.setName(name);
                std.setSex(sex);
                list.add(std);
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }finally {
            if(rs != null){
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(stmt != null){
                try {
                    stmt.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(conn != null){
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
        return list;
    }
}
